<?php

namespace control;
//管理员后台-批次明细表
use JetBrains\PhpStorm\NoReturn;

class batchDetailClass extends adIndexClass
{
    private const title = '批次明细表';
    private const page = 'batchDetail';
    private const table = 'inventory_record';
    private const tableMaterial = 'material';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'sourceTargetName' => [
                        'name'  => '往来单位',
                        'width' => 150,
                    ],
                    'code'             => [
                        'name'  => '{l.batchDetail.home.code}',
                        'width' => 150,
                    ],
                    'name'             => [
                        'name'  => '{l.batchDetail.home.name}',
                        'width' => 150,
                    ],
                    'typeName'         => [
                        'name'  => '{l.batchDetail.home.materialType}',
                        'width' => 150,
                    ],
                    'model'            => [
                        'name'  => '{l.batchDetail.home.model}',
                        'width' => 100,
                    ],
                    'time'             => [
                        'name'  => '{l.batchDetail.home.inDate}',
                        'width' => 180,
                        'sort'  => 1,
                    ],
                    'batch'            => [
                        'name'  => '{l.batchDetail.home.batch}',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'unit'             => [
                        'name'  => '{l.batchDetail.home.mainUnit}',
                        'width' => 80,
                    ],
                    'num'              => [
                        'name'  => '{l.batchDetail.home.unitNum}',
                        'width' => 100,
                        'sort'  => 1,
                    ],
                    'unit_one'         => [
                        'name'  => '{l.batchDetail.home.unit_one}',
                        'width' => 80,
                    ],
                    'unitOneNum'       => [
                        'name'  => '{l.batchDetail.home.unitOneNum}',
                        'width' => 100,
                    ],
                    'unit_two'         => [
                        'name'  => '{l.batchDetail.home.unit_two}',
                        'width' => 80,
                    ],
                    'unitTwoNum'       => [
                        'name'  => '{l.batchDetail.home.unitTwoNum}',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('batchDetail.home.code') => text(["name" => "mCode"]),
                    L('batchDetail.home.name') => text(["name" => "mName"]),
                    L('inventoryBalance.home.typeId') => materialClass::typeSelect(name: 'mTypeId', title: '请选择'),
                ],
                [
                    L('batchDetail.home.batch')   => text(array("name" => "batch")),
                    '客户名称' => clientProfileClass::kehuSelect(array('title' => '')),
                    '供应商' => supplierClass::supplierSelect(array('title' => '')),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询表单
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*列表页-查询结果*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'a.coid'        => self::$coid,
            'a.warehouseId' => $this->post('warehouseId'),
            'a.positionId'  => $this->post('positionId'),
        ];
        $like  = [
            'a.batch' => $this->post('batch'),
            'b.typePath' => $this->post('mTypeId'),
            'b.code' => $this->post('mCode'),
            'b.name' => $this->post('mName'),
        ];
        //生成查询语句
        $where       .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('khid')) {
            $where .= " and a.changesId in (select id from inventory_changes_detail where orderId in (select id from inventory_changes where targetId = '" . $this->post('khid') . "'))";
        }
        if ($this->post('supplierId')) {
            $where .= " and a.changesId in (select id from inventory_changes_detail where orderId in (select id from inventory_changes where targetId = '" . $this->post('supplierId') . "'))";
        }
        /*$having = "";
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');//允许零库存出库
        if(!$outAllowZero){
            $having = " HAVING total > 0 ";
        }
		$fieldArr                    = self::resolveField([
			'field' => '`id`, `coid`, `warehouseId`, `positionId`, `materialId`, `batch`, `num`, `inventoryId`, `inventoryMxId`, `moveId`, `isDefault`, `defaultPrice`, `time`, sum(num) as total',
			'group' => 'materialId, batch',
		]);*/
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page                        = $this->page([
            "table" => self::table . " as a join material as b on a.materialId = b.id",
            "field" => "a.*,b.code, b.name, b.model, b.unit, b.unit_one, b.unit_one_num, b.unit_two, b.unit_two_num, b.typeId, b.typeName",
            "where" => $where,//$fieldArr['group'].$having
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'sourceTargetName':
                        $inventory_changes_detail = query('inventory_changes_detail', "id = '$array[changesId]'");
                        $inventory_changes        = query('inventory_changes', "id = '$inventory_changes_detail[orderId]'");
                        $sourceTargetName         = clientProfileClass::getName($inventory_changes['targetId']);
                        $sourceTargetName         = $sourceTargetName ?: supplierClass::getName($inventory_changes['targetId']);
                        $row[]                    = $sourceTargetName;
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'unitOneNum':
                        $unitOneNum = (!$array['unit_one'] || empty((float)$array['unit_one_num'])) ? '' : self::formattingFigure($array['num'] / $array['unit_one_num'], 'numPrecision');
                        $row[]      = self::lostZero($unitOneNum, 'numPrecision');
                        break;
                    case 'unitTwoNum':
                        $unitTwoNum = (!$array['unit_two'] || empty((float)$array['unit_two_num'])) ? '' : self::formattingFigure($array['num'] / $array['unit_two_num'], 'numPrecision');
                        $row[]      = self::lostZero($unitTwoNum, 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        /*$numAll = find(array("table" => self::table, "field" => " sum(num) as total ", "single" => $where));
        $button .= "<span style='margin-left: 20px;font-weight: bold'>" . L('batchDetail.home.numTotal') . "：" . self::lostZero($numAll['total'], 'numPrecision') . "</span>";
        //查询结果
        $whereTotal = ' 1=1 ';
        $equal      = [
            'a.coid'        => self::$coid,
            'a.warehouseId' => $this->post('warehouseId'),
            'a.positionId'  => $this->post('positionId'),
        ];
        $like       = [
            'a.batch' => $this->post('batch'),
        ];
        //生成查询语句
        $whereTotal .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($targetWhere) {
            $whereTotal .= " and a.materialId IN (SELECT id FROM `" . self::tableMaterial . "` WHERE coid = '" . self::$coid . "' $targetWhere) ";
        }
        $fieldArr   = self::resolveField([
            'field' => 'sum(num)*c.avgPrice as total,a.materialId',
            'group' => 'a.materialId',
        ]);
        $moneyAll   = find(array(
            "table" => self::table . " as a INNER JOIN (
  SELECT MAX(id) AS id,materialId,any_value(`coid`) as coid
  FROM inventory_price GROUP BY materialId
) as b ON a.materialId = b.materialId and a.coid = b.coid JOIN inventory_price as c ON c.id = b.id ",
            "field" => $fieldArr['field'],
            "where" => $whereTotal . $fieldArr['group']
        ));
        $moneyTotal = array_sum(array_column($moneyAll['array'], 'total'));
        $button     .= "<span style='margin-left: 20px;font-weight: bold'>" . L('batchDetail.home.moneyTotal') . "：" . self::formattingFigure($moneyTotal) . "</span>" . space;*/
        $totalQuery = find([
            'table'  => self::table . " as a join material as b on a.materialId = b.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(a.num/b.unit_one_num),0) as unitOneNum,ifnull(sum(a.num/b.unit_two_num),0) as unitTwoNum",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'unitOneNum'   => self::lostZero($totalQuery['unitOneNum'], 'numPrecision'),
            'unitTwoNum' => self::lostZero($totalQuery['unitTwoNum'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $inventory_changes_detail = query('inventory_changes_detail', "id = '$array[changesId]'");
                $inventory_changes        = query('inventory_changes', "id = '$inventory_changes_detail[orderId]'");
                $sourceTargetName         = clientProfileClass::getName($inventory_changes['targetId']);
                $sourceTargetName         = $sourceTargetName ?: supplierClass::getName($inventory_changes['targetId']);
                $material                 = query(
                    self::tableMaterial,
                    " id = '$array[materialId]' ",
                    'code, name, model, unit, unit_one, unit_one_num, unit_two, unit_two_num, typeId, typeName'
                );
                $total                    = $array['num'];
                $unitOneNum               = (!$material['unit_one'] || empty((float)$material['unit_one_num'])) ? '' : self::formattingFigure($total / $material['unit_one_num'], 'numPrecision');
                $unitTwoNum               = (!$material['unit_two'] || empty((float)$material['unit_two_num'])) ? '' : self::formattingFigure($total / $material['unit_two_num'], 'numPrecision');
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '往来单位'=>$sourceTargetName,
                            '物料编码'=>$material['code'],
                            '物料名称'=>$material['name'],
                            '物料分类'=>$material['typeName'],
                            '规格型号'=>$material['model'],
                            '出入库日期'=>$array['time'],
                            '批次'=>$array['batch'],
                            '主单位'=> $material['unit'],
                            '主单位数量'=>self::lostZero($total, 'numPrecision'),
                            '辅单位1'=>$material['unit_one'],
                            '辅单位1数量'=>self::lostZero($unitOneNum, 'numPrecision'),
                            '辅单位2'=>$material['unit_two'],
                            '辅单位2数量'=> self::lostZero($unitTwoNum, 'numPrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('batchDetail.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('batchDetail.exportData.fileName') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'往来单位',
                    'aliasName'=>'往来单位',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'物料分类',
                    'aliasName'=>'物料分类',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'出入库日期',
                    'aliasName'=>'出入库日期',
                ],
                [
                    'columnName'=>'批次',
                    'aliasName'=>'批次',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'主单位数量',
                    'aliasName'=>'主单位数量',
                ],
                [
                    'columnName'=>'辅单位1',
                    'aliasName'=>'辅单位1',
                ],
                [
                    'columnName'=>'辅单位1数量',
                    'aliasName'=>'辅单位1数量',
                ],
                [
                    'columnName'=>'辅单位2',
                    'aliasName'=>'辅单位2',
                ],
                [
                    'columnName'=>'辅单位2数量',
                    'aliasName'=>'辅单位2数量',
                ],
            ]
        };
    }
}
